<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\model\room;


use app\common\model\BaseModel;
use app\common\model\user\User;


/**
 * RoomApartmentUserRecords模型
 * Class RoomApartmentUserRecords
 * @package app\common\model
 */
class RoomApartmentUserRecords extends BaseModel {

    protected $name = 'room_apartment_user_records';

    public function user() {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function room() {
        return $this->hasOne(RoomApartment::class, 'id', 'room_apartment_id')->with([
            "campus", "building",
        ]);
    }

    public function allRoomStat() {
        return $this->hasMany(RoomApartmentUserRecords::class, "user_id", "user_id")->with("roomStat");
    }

    public function roomStat() {
        return $this->hasOne(RoomApartment::class, "id", "room_apartment_id")
            ->field("*, (water_consumption * water_price / user_count) as water_total_fee")
            ->with([
                "campus", "building",
            ])
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 's_use_total';
                $query->where('device_type', 1);
            }], "use_total")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 's_price';
                $query->where('device_type', 1);
            }], "price")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 's_total_fee';
                $query->where('device_type', 1);
            }], "total_fee")
            ->withCount(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 's_device_count';
                $query->where('device_type', 1);
            }])
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'd_use_total';
                $query->where('device_type', 2);
            }], "use_total")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'd_price';
                $query->where('device_type', 2);
            }], "price")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'd_total_fee';
                $query->where('device_type', 2);
            }], "total_fee")
            ->withCount(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'd_device_count';
                $query->where('device_type', 2);
            }]);
    }


    // 数据初始化
    public function data_append($room_user_save) {
        foreach ($room_user_save as $user_key => &$user_value) {
            // $user_value['room_count'] = count(explode(",", $user_value['room_ids']));
            if (is_array($user_value['room_ids'])) {
                $user_value['room_count'] = count($user_value['room_ids']);
            } else {
                $user_value['room_count'] = count(explode(",", $user_value['room_ids']));
            }

            if ($user_value['is_log'] == 1) {
                if (!is_array($user_value['room_ids'])) {
                    $room_ids = explode(",", $user_value['room_ids']);
                } else {
                    $room_ids = $user_value['room_ids'];
                }
                $user_value['allRoomStat'] = RoomApartmentLog::where([
                    ["rid", "in", $room_ids],
                    ["log_time", "=", $user_value['log_time']],
                    ["log_date", "=", $user_value['log_date']],
                ])->select()->toArray();
            }

            $user_value['allRoomStat'] = array_map(function ($item) use ($user_value) {
                if ($user_value['is_log'] != 1) {
                    $item = $item['roomStat'];
                    $item['room_lift_fee'] = $item['lift_fee'] * 1;
                    $item['room_second_pressure_fee'] = $item['second_pressure_fee'] * 1;

                    // 房间如果有单独设置月用水量，则视为设备+1
                    $item['s_device_count'] = 1 * ($item['s_device_count'] + ($item['water_fee'] > 0 ? 1 : 0));
                    // 房间均水价
                    $item['room_s_price'] = 1 * sprintf("%.6f", ($item['s_price'] + $item['water_price']) / $item['s_device_count']);
                    // 人均用水量，（水表设备用水量 + 月用水量）/ 房间人数
                    $item['room_s_use_total'] = 1 * sprintf("%.2f", array_sum([
                                $item['s_use_total'], $item['water_consumption'],
                            ]) / $item['user_count']);
                    // 人均水费，（水表设备水费 + 月用水量）/ 房间人数
                    $item['room_s_total_fee'] = 1 * sprintf("%.6f", array_sum([
                                $item['s_total_fee'], $item['water_fee'],
                            ]) / $item['user_count']);
                    // 房间均电价
                    $item['room_d_price'] = 1 * sprintf("%.6f", $item['d_price'] / ($item['d_device_count'] * 1 <= 0 ? 1 : $item['d_device_count']));
                    // 人均用电量
                    $item['room_d_use_total'] = 1 * sprintf("%.2f", $item['d_use_total']) / $item['user_count'];
                    // 人均电费
                    $item['room_d_total_fee'] = 1 * sprintf("%.6f", $item['d_total_fee'] / $item['user_count']);
                    // 人均总费用
                    $item['room_all_total_fee'] = 1 * sprintf("%.2f", array_sum([
                            $item['room_lift_fee'], $item['room_second_pressure_fee'], $item['room_s_total_fee'], $item['room_d_total_fee'],
                        ]));
                }
                return $item;
            }, $user_value['allRoomStat']);

            $user_value['all_s_use_total'] = $this->array_sum_total($user_value['allRoomStat'], "room_s_use_total", 1, 2, 0);
            $user_value['all_s_price'] = 1 * $this->array_sum_total($user_value['allRoomStat'], "room_s_price", $user_value['room_count'], 6, 0);
            $user_value['all_s_total_fee'] = 1 * $this->array_sum_total($user_value['allRoomStat'], "room_s_total_fee", 1, 6, 0);

            $user_value['all_d_use_total'] = $this->array_sum_total($user_value['allRoomStat'], "room_d_use_total", 1, 2, 0);
            $user_value['all_d_price'] = 1 * $this->array_sum_total($user_value['allRoomStat'], "room_d_price", $user_value['room_count'], 6, 0);
            $user_value['all_d_total_fee'] = 1 * $this->array_sum_total($user_value['allRoomStat'], "room_d_total_fee", 1, 6, 0);

            $user_value['all_lift_fee'] = $this->array_sum_total($user_value['allRoomStat'], "lift_fee", 1, 2, 0);
            $user_value['all_second_pressure_fee'] = $this->array_sum_total($user_value['allRoomStat'], "second_pressure_fee", 1, 2, 0);
            $user_value['all_total_fee'] = 1 * $this->array_sum_total($user_value['allRoomStat'], "room_all_total_fee", 1, 2, 0);
        }
        return $room_user_save;
    }

    public function allDeviceStat() {
        return $this->hasMany(RoomApartmentUserRecords::class, "user_id", "user_id")->with([
            "room", "s_device_stat", "d_device_stat",
        ]);
    }

    public function sDeviceStat() {
        return $this->hasMany(RoomApartmentDevice::class, "rid", "room_apartment_id")->where("device_type", 1);
    }

    public function dDeviceStat() {
        return $this->hasMany(RoomApartmentDevice::class, "rid", "room_apartment_id")->where("device_type", 2);
    }

    public function allRoomLog() {
        return $this->hasMany(RoomApartmentUserRecords::class, "user_id", "user_id")->with([
            "roomLog"
        ]);
    }

    public function roomLog() {
        return $this->hasOne(RoomApartmentLog::class, "rid", "room_apartment_id");
    }

}
